__author__ = 'Oren'
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import datetime
from google.appengine.ext import ndb

class Message (ndb.Model):
    """Models an individual message entry with content(message) and id of KG"""

    msg =           ndb.TextProperty()
    title =         ndb.StringProperty()
    KG_id =         ndb.StringProperty()
    has_sent =      ndb.BooleanProperty()
    date =          ndb.DateTimeProperty()
    public_msg =    ndb.BooleanProperty()
    sender =        ndb.StringProperty()
    recips =        ndb.StringProperty()
    to_teacher =    ndb.BooleanProperty()

    @staticmethod
    def create_message_from_json(msg_info_json):
        """ Add a new message to datastore """
        data = json.loads(msg_info_json)
        msg = Message(KG_id = data.get("KG_id"),
                      date = datetime.datetime.now())
        if data.get("to_teacher") == 'True': # message from parent to teacher
            m = data.get("msg")
            t = data.get("title")
            msg.to_teacher = True
            msg.sender = data.get("child_id")
            msg.recips = data.get("KG_id")
            ma = m.decode("unicode-escape")
            msg.msg = ma.encode("UTF-8")
            ta = t.decode("unicode-escape")
            msg.title = ta.encode("UTF-8")
        else: # message from teacher to parents
            msg.to_teacher = False
            msg.sender = data.get("KG_id")
            msg.recips = data.get("recip_childs")
            msg.msg = data.get("msg")
            msg.title = data.get("title")
            if (data.get("recip_childs") == ""):
                msg.public_msg = True
            else:
                msg.public_msg =  False

        ent = msg.put()
        if ent is None:
            return -1
        return ent.get().key.id()



    @staticmethod
    def delete_message_by_ndb_id(ndb_id):
        """ Delete exist message from datastore by given id from ndb (given to web on create)
            Always returns 1 """
        ndb.Key(Message, ndb_id).delete()
        return 1


    @staticmethod
    def get_all_public_messages_by_KG_id(data_json):
        """ returns all public messages of kindergarten by his id """
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        messages = ndb.gql("SELECT * FROM Message WHERE KG_id = :teacher ORDER BY date", teacher=str(given_KG_id))
        res = []
        for m in messages:
            # if m.recips == "" or m.recips is None:
            if m.recips == "" or m.recips == "":
                data = {"msg": m.msg, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": m.key.id(), "recip_childs": ""}
                data_s = json.dumps(data)
                res.append(data_s)
        res.reverse()
        return res

    @staticmethod
    def delete_img_from_msg(text):
        """ delete image link from text """
        res = ""
        a = text.index("img src=")
        start = a-1
        end = a
        while (text[end] != '>'):
            end += 1
        end += 1
        first = text[:start]
        second = text[end:]
        res = first + second
        return res

    @staticmethod
    def parse_img(text):
        """ parse image link from text """
        res = ""
        a = text.split("img src=")
        if len(a) == 1:
            return 'null'
        b = a[1].split(" width")
        res = b[0][1:-1]
        return res

    @staticmethod
    def get_all_public_messages_by_KG_id_for_android(data_json):
        """ return all public messages for a specific kindergarten (for android app) """
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        messages = ndb.gql("SELECT * FROM Message WHERE KG_id = :teacher ORDER BY date", teacher=str(given_KG_id))
        res = []
        for m in messages:
            # if m.recips == "" or m.recips is None:
            if m.recips == "" or m.recips == "":
                mes = m.msg
                r = Message.parse_img(mes)
                if r != 'null':
                    mes = Message.delete_img_from_msg(mes)
                data = {"msg": mes, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": m.key.id(), "recip_childs": "", "img": r}
                data_s = json.dumps(data)
                res.append(data_s)
        res.reverse()
        return res

    @staticmethod
    def get_all_private_messages_by_child_id(data_json):
        """ returns all private messages of teacher with child by his id """
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        given_child_id = data.get("child_id")
        messages = ndb.gql("SELECT * FROM Message WHERE KG_id = :teacher ORDER BY date", teacher=str(given_KG_id))
        res = []
        for m in messages:
            if (m.sender == given_child_id): # message from parent to teacher or from teacher to parents
                data = {"msg": m.msg, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": str(m.key.id()), "to_teacher": "true"}
                data_s = json.dumps(data)
                res.append(data_s)
            if(m.recips != ""):
                if (given_child_id in m.recips):

                    data = {"msg": m.msg, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": str(m.key.id()), "to_teacher": "false"}
                    data_s = json.dumps(data)
                    res.append(data_s)
        res.reverse()
        res_json = json.dumps(res)
        return res_json


    @staticmethod
    def get_all_private_messages_by_child_id_for_android(data_json):
        """ return all private messages for a specific child (for android app) """
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        given_child_id = data.get("child_id")
        messages = ndb.gql("SELECT * FROM Message WHERE KG_id = :teacher ORDER BY date", teacher=str(given_KG_id))
        res = []
        for m in messages:
            if (m.sender == given_child_id): # message from parent to teacher or from teacher to parents
                data = {"msg": m.msg, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": str(m.key.id()), "to_teacher": "true"}
                data_s = json.dumps(data)
                res.append(data_s)
            if(m.recips != ""):
                if (given_child_id in m.recips):
                    mes = m.msg
                    r = Message.parse_img(mes)
                    if r != 'null':
                        mes = Message.delete_img_from_msg(mes)
                    # return mes
                    data = {"msg": mes, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": str(m.key.id()), "to_teacher": "false", "img": r}
                    data_s = json.dumps(data)
                    res.append(data_s)
        res.reverse()
        return res


    @staticmethod
    def get_all_teacher_private_messages_from_child_id(data_json):
        """ return list of jsons with all messages from child's parents to teacher with given KG id and for child's parents"""
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        child_id = data.get("child_id")
        messages = ndb.gql("SELECT * FROM Message WHERE KG_id = :teacher", teacher=given_KG_id)
        res = []
        for m in messages:
            if m.to_teacher is True:
                data = {"msg": m.msg, "title": m.title, "date": str(m.date.strftime("%d-%m-%Y %H:%M")), "id": str(m.key.id()), "from_child": m.from_child}
                data_s = json.dumps(data)
                res.append(data_s)
            else:
                arr = []
                recips = m.recip_childs.split(',')
                for recip in recips:
                    arr.append(recip)
                    if child_id in arr:
                        data = {"msg": m.msg, "title": m.title, "date": str(m.date), "id": str(m.key.id()), "recip_childs": arr}
                        data_s = json.dumps(data)
                        res.append(data_s)
        res_json = json.dumps(res)
        return res_json
